package com.polytech.rsa;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Random;


public class RsaOaep {
	
	private BigInteger x,y,r;
	private int k0=16;
	
	public RsaOaep() {
		
	} 
	private BigInteger hash(BigInteger value){
		 BigInteger res = null;
		try {
			MessageDigest digest=MessageDigest.getInstance("SHA-256");
			digest.update(value.toByteArray());
			res=new BigInteger(digest.digest());
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return res;
	}
	private BigInteger oaep(BigInteger message){
		r=new BigInteger(k0, new Random());
		x=message.xor(hash(r));
		y=r.xor(hash(x));
		BigInteger res = concate(x,y);
		return res;
		
	}
	
	public BigInteger encrypt(BigInteger message,BigInteger publicKey,BigInteger n){
		
		BigInteger oaep = oaep(message);
		return oaep.modPow(publicKey, n);
	}
	
	public BigInteger decrypt(BigInteger privateKey,BigInteger cipher,BigInteger n){
		
		 BigInteger moaep = cipher.modPow(privateKey,n);
		 
		 return null;
		
	}
	private static BigInteger concate(BigInteger x2, BigInteger y2) {
        byte res[]=new byte[x2.toByteArray().length+y2.toByteArray().length];
        
        for(int i=0;i<x2.toByteArray().length;i++)
        	res[i]=x2.toByteArray()[i];
        
        for(int i=0;i<y2.toByteArray().length;i++)
        	res[i+x2.toByteArray().length]=y2.toByteArray()[i];
        
		return new BigInteger(res);
	}
	
	public static void main(String[] args) {
		RSAKeysGenerator generator=new RSAKeysGenerator();
		BigInteger publicKey=generator.generatePublicKey();
		BigInteger privateKey=generator.generatePrivateKey();
	
		
	   BigInteger message=new BigInteger("12345");
	   RsaOaep rsaOaep=new RsaOaep();
	   System.err.println("paire de clés(privateKey="+privateKey+","+publicKey+")");
	   System.out.println("message:"+message.toString());
	   BigInteger cipher = rsaOaep.encrypt(message,publicKey, generator.getN());
	   System.out.println("cipher:"+cipher.toString());
	   System.out.println("text dechiffré:"+rsaOaep.decrypt(privateKey,cipher,generator.getN()));

	   
	}

}
